package com.soft.springhrms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soft.springhrms.mapper.UsersMapper;
import com.soft.springhrms.pojo.Employees;
import com.soft.springhrms.pojo.Requests;
import com.soft.springhrms.mapper.*;
import com.soft.springhrms.pojo.*;
import com.soft.springhrms.service.EmployeesService;
import com.soft.springhrms.mapper.EmployeesMapper;
import com.soft.springhrms.vo.RequestVO;
import com.soft.springhrms.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author DELL
 * @description 针对表【employees】的数据库操作Service实现
 * @createDate 2024-11-16 18:48:18
 */
@Service
public class EmployeesServiceImpl extends ServiceImpl<EmployeesMapper, Employees>
        implements EmployeesService {
    @Autowired
    private EmployeesMapper employeesMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private PositionsMapper positionsMapper;
    @Autowired
    private EmployeeChangesMapper employeeChangesMapper;
    @Autowired
    private DepartmentsMapper departmentsMapper;

    @Override
    public IPage<Employees> getEmployeesWithPagination(int page, int size, String keyword) {
        Page<Employees> employeePage = new Page<>(page, size);
        return employeesMapper.getEmployeesWithPagination(employeePage, keyword);
    }

    @Transactional
    @Override
    public void EditEmployees(Employees employees) {
        //根据前端传回的数据更改users表和employees表（使用事务保证一致性）
        Users EditUser = new Users();
        //根据传入的employees实体类中的扩展属性创建Users对象并对数据库进行更新操作
        String UserName = employees.getUsername();
        String RoleName = employees.getRoleName();
        String PhoneNumber = employees.getPhoneNumber();
        Integer UserId = employees.getUserId();
        QueryWrapper query = new QueryWrapper<>();
        query.eq("name", RoleName);
        Roles roles = rolesMapper.selectOne(query);
        Integer RoleId = roles.getId();
        EditUser.setRoleId(RoleId);
        EditUser.setUsername(UserName);
        EditUser.setPhoneNumber(PhoneNumber);
        EditUser.setUpdatedAt(new Date());
        EditUser.setId(UserId);
        usersMapper.updateById(EditUser);
        //更改职位后，要将职位变动记录插入到职位变动记录表中
        //首先判断职位和之前一致不一致
        Employees employees2 = employeesMapper.selectById(employees.getId());
        if(employees2!=null)
        {if(employees2.getPositionId()!=null)
        {
        if (!employees.getPositionId().equals(employees2.getPositionId())) {
            Positions pold =positionsMapper.selectById(employees2.getPositionId());
            Positions pnew =positionsMapper.selectById(employees.getPositionId());
            EmployeeChanges ec = new EmployeeChanges();
            ec.setEmployeeId(employees.getId());
            ec.setPositionChangeHistory("职位从" + pold.getName() + "变动到" + pnew.getName());
            employeeChangesMapper.insert(ec);
        }}}
        employeesMapper.insertOrUpdate(employees);
    }

    @Override
    public Integer countByDepartment(Integer departmentId) {
        return employeesMapper.countByDepartment(departmentId);
    }

    @Override
    public Integer countByPosition(Integer positionId) {
        return employeesMapper.countByPosition(positionId);
    }

    @Override
    public Employees getEmployeeInfo(Integer id) {
        Employees employees=employeesMapper.selectById(id);if(employees!=null){
            if(employees.getPositionId()!=null){
            employees.setPositionName(positionsMapper.selectById(employees.getPositionId()).getName());}
            if(employees.getDepartmentId()!=null){
                employees.setDepartmentName(departmentsMapper.selectById(employees.getDepartmentId()).getName());
            }
        }
        return employees;
    }




    public ResultVO updateEmploymentStatus(Map<String, Object> params) {
        Integer employeeId = (Integer) params.get("employeeId");
        String employmentStatus = (String) params.get("employmentStatus");

        if (employeeId == null || employmentStatus == null) {
            return ResultVO.error(400, "参数缺失");
        }

        try {
            Employees employee = employeesMapper.selectById(employeeId);
            if (employee == null) {
                return ResultVO.error(404, "员工不存在");
            }
            employee.setEmploymentStatus(employmentStatus);
            employee.setResignationDate(new Date());
            employeesMapper.updateById(employee);
            return ResultVO.success("员工状态更新成功");
        } catch (Exception e) {
            return ResultVO.error(500, "更新失败：" + e.getMessage());
        }
    }

    @Override
    public ResultVO getApproveSalaryById(Integer employeeId) {
        QueryWrapper<Employees> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", employeeId);
        Employees employees = employeesMapper.selectOne(queryWrapper);
        if (employees != null) {
            return ResultVO.success(employees);
        }
        return ResultVO.error(404, "未找到对应请求记录");
    }

    @Override
    public IPage<Employees> getEmployeesAsNoAttendance(int page, int size, String date) {
        Page<Employees> employeePage = new Page<>(page, size);
        return employeesMapper.getEmployeesAsNoAttendance(employeePage,date);
    }

    @Override
    public ResultVO getDepartmentEcharts() {
        List<Map<String,Object>> departmentCount=employeesMapper.getDepartmentEcharts();
        return ResultVO.success(departmentCount,"获取部门信息成功");
    }

    @Override
    public ResultVO getPositionEcharts(Integer departmentId) {
        List<Map<String,Object>> positionCount=employeesMapper.getPositionEcharts(departmentId);
        return ResultVO.success(positionCount,"获取职位信息成功");
    }

}




